package star.oath.framework.generate.template;

import star.oath.framework.generate.CodeGenerator;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class ServiceImplementsClassTemplate {
    /**
     * 根据实体类的全限定名生成对应的 ServiceImpl 类
     * @param fullyQualifiedEntityName
     */
    public void generateServiceImplementsClass(String fullyQualifiedEntityName) {
        if (fullyQualifiedEntityName == null || fullyQualifiedEntityName.trim().isEmpty()) {
            throw new IllegalArgumentException("实体类全限定名不能为空");
        }

        // 1. 拆分类名和包名
        int lastDot = fullyQualifiedEntityName.lastIndexOf('.');
        if (lastDot == -1) {
            throw new IllegalArgumentException("无效的全限定类名: " + fullyQualifiedEntityName);
        }

        String packageName = fullyQualifiedEntityName.substring(0, lastDot);
        String className = fullyQualifiedEntityName.substring(lastDot + 1);

        // 2. 校验类名合法性
        if (!CodeGenerator.VALID_CLASS_NAME.matcher(className).matches()) {
            throw new IllegalArgumentException("非法的类名: " + className);
        }

        // 3. 检查是否在 model 包下
        if (!packageName.endsWith(".model")) {
            throw new IllegalArgumentException("实体类必须位于 .model 包下，当前包: " + packageName);
        }

        // 4. 推导相关类名和包名
        // Mapper
        String mapperPackageName = packageName.substring(0, packageName.length() - "model".length()) + "mapper";
        String mapperClassName = className + "Mapper";
        String mapperFullyQualifiedName = mapperPackageName + "." + mapperClassName;

        // Service
        String servicePackageName = packageName.substring(0, packageName.length() - "model".length()) + "service";
        String serviceClassName = className + "Service";
        String serviceFullyQualifiedName = servicePackageName + "." + serviceClassName;

        // ServiceImpl
        String serviceImplPackageName = servicePackageName + ".impl";
        String serviceImplClassName = className + "ServiceImpl";

        // 5. 构建 ServiceImpl 类内容
        String serviceImplContent = String.format(
                "package %s;\n\n" +
                        "import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\n" +
                        "import %s;\n" + // Mapper
                        "import %s;\n" + // Entity
                        "import %s;\n" + // Service Interface
                        "import org.springframework.stereotype.Service;\n\n" +
                        "@Service\n" +
                        "public class %s extends ServiceImpl<%s, %s> implements %s {\n" +
                        "}\n",
                serviceImplPackageName,
                mapperFullyQualifiedName,
                fullyQualifiedEntityName,
                serviceFullyQualifiedName,
                serviceImplClassName,
                mapperClassName,
                className,
                serviceClassName
        );

        // 6. 构建 ServiceImpl 文件路径
        String serviceImplDirPath = CodeGenerator.SRC_MAIN_JAVA + serviceImplPackageName.replace('.', '/');
        Path serviceImplDir = Paths.get(serviceImplDirPath);
        try {
            Files.createDirectories(serviceImplDir);
            Path serviceImplFile = serviceImplDir.resolve(serviceImplClassName + ".java");
            Files.write(serviceImplFile, serviceImplContent.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            System.out.println("✅ ServiceImpl 类已生成: " + serviceImplFile.toAbsolutePath());
        } catch (IOException e) {
            System.err.println("❌ 生成 ServiceImpl 类失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}